package com.example.exp3.service;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class COVID19CSV {

    Iterable<CSVRecord> records = null;
    List<CSVRecord> recordList = new ArrayList<>();

    public void saveCsv(String csv_content) throws IOException {
        FileWriter out = new FileWriter("covid19.csv");
        out.write(csv_content);
        out.close();
    }

    public List<CSVRecord> getAll() {
        return recordList;
    }

    public String requestForCSV() {
        RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        return template.getForObject(url, String.class);
    }

    public Iterable<CSVRecord> readCSV() {
        Reader in = null;
        try {
            in = new InputStreamReader(new BOMInputStream(new FileInputStream("covid19.csv")));
            records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return records;

    }

    public void updateCsv() throws IOException {
        String csv_content = this.requestForCSV();
        if (csv_content != null) {
            this.saveCsv(csv_content);
        }
        records = this.readCSV();
        if(!recordList.isEmpty()) recordList.clear();
        int count = 0;
        for (CSVRecord record : records) {
            recordList.add(record);
        }
    }


}
